/*
运用按位异或（无需创建临时变量），交换两个变量的数值
数组元素头尾两端依次对调
*/
#include <stdio.h>
#include <string.h>

void inplace_swap(int *a, int *b);
void reverse_array(int *array, int len);
void print_array(int *array, int len);

int main(int argc, const char *argv[])
{
    int ival1 = 6789;
    int ival2 = 12345;
    int array[5] = {1, 2, 3, 4, 5};
    int len = sizeof(array)/sizeof(array[0]);

    printf("ival1 = %d\tival2 = %d\n", ival1, ival2);
    // 按位异或，交换变量
    inplace_swap(&ival1, &ival2);
    printf("ival1 = %d\tival2 = %d\n", ival1, ival2);

    printf("未交换前的数组：");
    print_array(array, len);

    // 数组元素头尾两端依次对调
    reverse_array(array, len);
    printf("数组元素头尾两端依次对调：");
    print_array(array, len);

    return 0;
}

/* 按位异或，交换变量 */
void inplace_swap(int *a, int *b)
{
    // a ^ a = 0
    // (a ^ b) ^ a = b
    *b = *a ^ *b;
    // *a = *a ^ (*a ^ *b) = *a ^ *a ^ *b = 0 ^ *b = *b
    *a = *a ^ *b;
    // *b = *b ^ (*a ^ *b) = *a ^ (*b ^ *b) = *a ^ 0 = *a 
    *b = *a ^ *b;
}

/* 数组元素头尾两端依次对调 */
void reverse_array(int *array, int len)
{
    int first, last;

    for (first=0,last=len-1;first<last;first++,last--) {
        inplace_swap(array+first, array+last);
    }
}

/* 打印数组元素 */
void print_array(int *array, int len)
{
    for (int i=0;i<len;i++) {
        printf("%d ", *(array+i));
    }

    printf("\n");
}